package com.iplant.basic.serviceImpl.dao.mss;

import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.basic.service.po.mss.MSSUnitGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class MSSUnitGroupDAO extends BaseDAO {

	private static MSSUnitGroupDAO Instance = null;
	private static Logger logger = LoggerFactory.getLogger(MSSUnitGroupDAO.class);

	private MSSUnitGroupDAO() {
		super();

		setTableName("mss_unitgroup");
	}

	public static MSSUnitGroupDAO getInstance() {
		if (Instance == null)
			Instance = new MSSUnitGroupDAO();
		return Instance;
	}

	public void MSS_UpdateUnitGroup(BMSEmployee wLoginUser, MSSUnitGroup wUnitGroup,
			OutResult<Integer> wErrorCode) {
		wErrorCode.set(0);

		try {
			if (wUnitGroup == null || StringUtils.isEmpty(wUnitGroup.Name)) {
				wErrorCode.set(ExceptionTypes.Parameter.getValue());
				return;
			}
			MSSUnitGroup wUnitGroupO = this.MSS_CheckUnitGroup(wLoginUser, wUnitGroup, wErrorCode);
			if (wUnitGroupO.ID > 0) {
				wErrorCode.set(ExceptionTypes.Duplication.getValue());
			}
			if (wErrorCode.Result != 0)
				return;

			wUnitGroup.GroupFullName = "";
			if (wUnitGroup.ParentGroupID > 0) {
				wUnitGroupO = this.MSS_QueryUnitGroup(wLoginUser, wUnitGroup.ParentGroupID, "", wErrorCode);
				if (wErrorCode.Result != 0)
					return;

				if (wUnitGroupO == null || wUnitGroupO.ID <= 0) {
					wUnitGroup.ParentGroupID = 0;

				} else {

					wUnitGroup.GroupFullName = StringUtils.Format("{0}{1}/", wUnitGroupO.GroupFullName,
							wUnitGroupO.Name);
				}
			}

			Map<String, Object> wParams = new HashMap<String, Object>();

			wParams.put("Name", wUnitGroup.Name);
			wParams.put("Code", wUnitGroup.Code);
			wParams.put("ParentGroupID", wUnitGroup.ParentGroupID);
			wParams.put("GroupFullName", wUnitGroup.GroupFullName);
			wParams.put("Description", wUnitGroup.Description);

			wParams.put("EditorID", wLoginUser.getID());
			wParams.put("EditTime", Calendar.getInstance());
			wParams.put("Active", wUnitGroup.Active);

			if (wUnitGroup.ID > 0) {
				wParams.put("ID", wUnitGroup.ID);
				super.Update(super.getTableName("mss_unitgroup"), "ID", wParams);
			} else {
				wParams.put("CreatorID", wLoginUser.getID());
				wParams.put("CreateTime", Calendar.getInstance());
				wUnitGroup.ID = super.Insert(super.getTableName("mss_unitgroup"), wParams);
			}

		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());
			logger.error("MSS_UpdateUnitGroup", ex);
		}
	}

	public void MSS_ActiveUnitGroup(BMSEmployee wLoginUser, MSSUnitGroup wUnitGroup, int wActive,
			OutResult<Integer> wErrorCode) {
		wErrorCode.set(0);
		// 判断客户信息是否存在(中国：统一社会信用代码，国外:提醒是否有重复）

		try {
			if (wUnitGroup == null || wUnitGroup.ID <= 0) {
				wErrorCode.set(ExceptionTypes.Parameter.getValue());
				return;
			}

			Map<String, Object> wParams = new HashMap<String, Object>();

			wParams.put("ID", wUnitGroup.ID);
			wParams.put("EditorID", wLoginUser.getID());
			wParams.put("EditTime", Calendar.getInstance());
			wParams.put("Active", wActive);
			super.Update(super.getTableName("mss_unitgroup"), "ID", wParams);

		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());

			logger.error("MSS_ActiveUnitGroup", ex);
		}
	}

	public List<MSSUnitGroup> MSS_QueryUnitGroupList(BMSEmployee wLoginUser, String wName, int wParentGroupID,
			String wGroupFullName, int wActive, Pagination wPagination, OutResult<Integer> wErrorCode) {
		return this.MSS_QueryUnitGroupList(wLoginUser, -1, "", wName, wParentGroupID, wGroupFullName, wActive,
				wPagination, wErrorCode);
	}

	private List<MSSUnitGroup> MSS_QueryUnitGroupList(BMSEmployee wLoginUser, int wID, String wCode,
			String wName, int wParentGroupID, String wGroupFullName, int wActive, Pagination wPagination,
			OutResult<Integer> wErrorCode) {
		List<MSSUnitGroup> wMSSUnitGroupList = new ArrayList<MSSUnitGroup>();
		wErrorCode.set(0);

		try {

			// Step02:查询
			Map<String, Object> wParams = new HashMap<String, Object>();
			String wSQLText = "";
			wSQLText = StringUtils.Format(
					"Select t.*,t3.Name as CreatorName ,t4.Name as EditorName, t2.Name as ParentGroupName,"
							+ " t2.Code as ParentGroupCode,COUNT(t5.ID) as ItemCount,COUNT(t6.ID) as UnitCount  from {0}.mss_unitgroup t  "
							+ " left join {0}.mss_unitgroup t2 on t.ParentGroupID=t2.ID "
							+ " left join {0}.mbs_user t3 on t.CreatorID=t3.ID "
							+ " left join {0}.mbs_user t4 on t.EditorID=t4.ID "
							+ " left join {0}.mss_unitgroup t5 on t5.ParentGroupID=t.ID "
							+ " left join {0}.mss_unit t6 on t6.GroupID=t.ID "
							+ " where (:ID<=0 or  t.ID=:ID) and (:Code =''''  or  t.Code=:Code)"
							+ " AND (:ParentGroupID<0 or  t.ParentGroupID=:ParentGroupID)  AND (:Active<0 or  t.Active=:Active) "
							+ " AND (:Name = '''' or  t.Name like :Name) AND (:GroupFullName = '''' or  t.GroupFullName like :Name)  group by t.ID",
					super.getDBName());

			wSQLText = this.DMLChange(wSQLText);

			wParams.put("ID", wID);
			wParams.put("Code", wCode);
			wParams.put("ParentGroupID", wParentGroupID);
			wParams.put("Active", wActive);
			wParams.put("Name", StringUtils.isEmpty(wName) ? "" : ("%" + wName + "%"));
			wParams.put("GroupFullName", StringUtils.isEmpty(wGroupFullName) ? "" : (wGroupFullName + "%"));

			wMSSUnitGroupList = super.QueryForList(wSQLText, wParams, wPagination, MSSUnitGroup.class);

			// Step03:配置系统
		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());
			logger.error("MSS_QueryUnitGroupList", ex);
		}
		return wMSSUnitGroupList;
	}

	public MSSUnitGroup MSS_QueryUnitGroup(BMSEmployee wLoginUser, int wID, String wCode,
			OutResult<Integer> wErrorCode) {
		MSSUnitGroup wResult = new MSSUnitGroup();
		wErrorCode.set(0);

		try {
			List<MSSUnitGroup> wList = null;
			if (wID > 0) {
				wList = this.MSS_QueryUnitGroupList(wLoginUser, wID, "", "", -1, "", -1, Pagination.getDefault(),
						wErrorCode);

			} else if (StringUtils.isNotEmpty(wCode)) {
				wList = this.MSS_QueryUnitGroupList(wLoginUser, -1, wCode, "", -1, "", -1, Pagination.getDefault(),
						wErrorCode);
			}
			if (wList != null && wList.size() > 0) {
				wResult = wList.get(0);
			}
		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());
			logger.error("MSS_QueryUnitGroupByID", ex);
		}
		return wResult;
	}

	public MSSUnitGroup MSS_CheckUnitGroup(BMSEmployee wLoginUser, MSSUnitGroup wMSSUnitGroup,
			OutResult<Integer> wErrorCode) {
		MSSUnitGroup wUnitGroup = new MSSUnitGroup();
		wErrorCode.set(0);

		try {

			// Step0:查询
			Map<String, Object> wParams = new HashMap<String, Object>();
			String wSQLText = StringUtils.Format("Select * from {0}.mss_unitgroup "
					+ " where ID!=:ID  AND ( (Name =:Name and ParentGroupID=:ParentGroupID) or (:Code != '''' and Code=:Code)) ",
					super.getDBName());
			wParams.clear();
			wParams.put("ID", wMSSUnitGroup.ID);
			wParams.put("Name", wMSSUnitGroup.Name);
			wParams.put("ParentGroupID", wMSSUnitGroup.ParentGroupID);
			wParams.put("Code", wMSSUnitGroup.Code);

			wSQLText = this.DMLChange(wSQLText);
			List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams);
			for (Map<String, Object> wSqlDataReader : wQueryResultList) {
				wUnitGroup.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
				wUnitGroup.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
				wUnitGroup.Code = StringUtils.parseString(wSqlDataReader.get("Code"));
				wUnitGroup.GroupFullName = StringUtils.parseString(wSqlDataReader.get("GroupFullName"));

				wUnitGroup.ParentGroupID = StringUtils.parseInt(wSqlDataReader.get("ParentGroupID"));
				wUnitGroup.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
				wUnitGroup.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
				wUnitGroup.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
				wUnitGroup.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
				wUnitGroup.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));

			}

		} catch (Exception ex) {
			wErrorCode.set(ExceptionTypes.DBSQL.getValue());
			logger.error("MSS_CheckUnitGroup", ex);
		}
		return wUnitGroup;
	}

}
